import upLoadFile from './upLoadFile.js'
import store from '../store/index.js'
class  MyMessage{
	constructor({accept_type,type,content,ws}) {//模拟ws返回消息数据
		this.accept_id=store.state.chat.chatObjectInfo.chatObjectData.id
		this.accept_type=accept_type
		this.account=store.state.chat.chatObjectInfo.chatObjectData.account
		this.content=content
		this.create_time=new Date().toLocaleString()
		this.history_id=''//这个我这里无法控制 且暂时无需用到
		this.id=store.state.chat.chatObjectInfo.chatObjectData.id
		this.otherClient=null
		this.picture=store.state.chat.chatObjectInfo.chatObjectData.picture
		this.send_user_id=store.state.user.user.id
		this.type=type
		this.ws = ws
		this.ifSendSussess='正在发送' //该消息发送状态
		this.time_id=new Date().getTime()
		this.sendAccount=store.state.user.user.account
		this.sendPicture=store.state.user.user.picture
	}
	addMessageList=(data)=>{ //首先添加到当前聊天列表中， 并更新聊天对象列表 或 添加到聊天对象列表
		
	store.commit('chat/setChatMessageList',[...store.state.chat.chatObjectInfo.chatMessageList,data])//添加到消息列表
	var newMessageData=store.state.chat.chatObjectList.find((object)=>object.id==data.id && object.accept_type==data.accept_type) //查找该聊天用户
	var index=store.state.chat.chatObjectList.findIndex((object)=>object.id==data.id && object.accept_type==data.accept_type)
	if(newMessageData){//存在该用户则覆盖原来的记录						
		var newChatObjectList=[...store.state.chat.chatObjectList]		
						
			newMessageData.content=data.content
			newMessageData.create_time=data.create_time
		newChatObjectList.splice(index,1)							
		store.commit('chat/setChatObjectList',[newMessageData,...newChatObjectList])
	}else{//不存在则push进去
							
			data.picture=store.state.chat.chatObjectInfo.chatObjectData.picture
			data.account=store.state.chat.chatObjectInfo.chatObjectData.account
		
		store.commit('chat/setChatObjectList',[data,...store.state.chat.chatObjectList])						
		}
		
		
	//接下来通过ws发送消息
	this.sendMessage()
	}
	sendMessage=async ()=>{
		
		var sendContent=this.content //发送的消息默认为文本类型直接 以文本内容为消息内容 
		if(this.type==2 || this.type==3){//为2 或 3则是文件类型 需要先进行上传文件再发送
			sendContent =	await this.uploadFile()  //如果是文件类型 原content为本地连接 我们需要获取上传成功后的在线连接为消息内容发给对方
		}
	
		this.ws.sendMessage({
			msg: {
				postType: 'postMessage',
				accept_id: this.accept_id,
				accept_type:this.accept_type,
				type: this.type,
				content: sendContent,
				time_id:this.time_id
			}
		})
	}
	uploadFile=()=>{
		return new Promise(async (resolve,reject)=>{
			var result= await upLoadFile({
				url: '/blientBoxuser/upload',
				header: {
					token:store.state.user.token
				},
				data: {
					file: this.content,
				}
			})
			var fileUrl=JSON.parse(result[1].data).data.data
			resolve(fileUrl)
		})
	}
}


export default MyMessage